__author__ = 'jlin@systemsbiology.org'
import os
import sys
import ConfigParser
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
try: import json #python 2.6 included simplejson as json
except ImportError: import simplejson as json

# Register the streaming http handlers with urllib2
register_openers()

sam_hash = {}
files_hash = {}
cgs_input_hash = {}

def getAlignedPath(dir):
        list = dir.rsplit("/",1)
        return list[0]

def renamedBuildPath(dir, aligneddir, key):
        os.rename(dir, aligneddir + "/" + key)

def populateStrainSeq(dir):
	global cgs_input_hash
	list = dir.split("/")
	#/solexa/dudley/genome_assembly/YO502/YSEQ4/unprocessed_reads/alignment_1/build_26-Combined
	cgs_input_hash["YCGSSeqRun"] = list[5]
	#cgs_input_hash["YCGSStrain"] = list[4].replace("YO", "YO_")
	cgs_input_hash["YCGSStrain"] = list[4]

def createSymlink(src, dst, linkname, dstname):
	global sam_hash
	srcname = os.path.join(dst, dstname)
        symname = os.path.join(src, linkname + ".mut")
	#srcname.replace("YO_", "YO")
	#symname.replace("YO_", "YO")
	print "source_file %s symlink %s" %(srcname, symname)
	os.symlink(srcname, symname)
	#symlink for bam/bai
	bamlink = os.path.join(src, linkname + ".bam")
	os.symlink(sam_hash["cgsbam"], bamlink)
	bailink = os.path.join(src, linkname + ".bai")
	os.symlink(sam_hash["cgsbai"], bailink)

def cgs_submit(datapath, symlink_webpath, config):
	global cgs_input_hash, sam_hash, files_hash
	alignedPath = getAlignedPath(datapath)
	populateStrainSeq(alignedPath)	
	#build bam and bai json
	sam_hash["cgsbam"] = alignedPath + "/aligned_reads/aligned_reads_sorted_IGV.bam"
	sam_hash["cgsbai"] = alignedPath + "/aligned_reads/aligned_reads_sorted_IGV.bai"	
	for (root, dirs, files) in os.walk(datapath):
		for file in files:
			print "create json for file:" + file
			files_hash[cgs_input_hash["YCGSSeqRun"] + "_" + cgs_input_hash["YCGSStrain"] + "_" + file.split(".")[0]] = file			
	cgs_input_hash["user"] = config.get("cgs_lims", "user")
	cgs_input_hash["password"]=config.get("cgs_lims", "password")#cgs_s9bm!t"
	cgs_input_hash["YCGSDudleyProject"] ="Dudley Paired End"
	cgs_input_hash["cgsbam"] = sam_hash["cgsbam"]
	cgs_input_hash["cgsbai"] = sam_hash["cgsbai"]
	for pf_key in files_hash:
		cgs_input_hash[pf_key] = open(datapath + "/" + files_hash[pf_key])
	#cgs_input_hash = {"ra_changes":open(datapath + "/RA.mut"), "bd":open(datapath + "/IA.mut"), "dn_changes":open(datapath + "/DN.mut"), "user":"gcromie", "password":"cgs_s9bm!t","YCGSSeqRun":"YSEQ4", "YCGSStrain":"YO_486", "YCGSDudleyProject":"Dudley Paired End", "cgsbam":sam_hash["cgsbam"], "cgsbai":sam_hash["cgsbai"]}
	
	# headers contains the necessary Content-Type and Content-Length
	# datagen is a generator object that yields the encoded parameters
	datagen, headers = multipart_encode(cgs_input_hash)

	# Create the Request object
	#http://ravioli:8080/dudley-lims/sequencing/cgs/submitx
	limsControllerUrl = config.get("cgs_lims", "limsControllerUrl")
	request = urllib2.Request(limsControllerUrl, datagen, headers)
	# Actually do the request, and get the response
	results = json.load(urllib2.urlopen(request))
	cgsKey = results['YCGSKey']
	print 'cgsKey ' + cgsKey + ' status:' + results['status']
	f = open(datapath + '/' + cgsKey + '.dat', 'w')
	f.write(json.dumps(results))
	f.close()
	#create symlinks and rename build folder
	renamedBuildPath(datapath, alignedPath, cgsKey)
	#createSymlinks for each mutation files and bam bai
	igvMutationSourcePath = config.get("cgs_lims", "igvMutationSourcePath")
	for kv in files_hash:
		if (files_hash[kv].find(".mut") > -1):
			print "create symlinks for key %s mut file %s" % (kv, files_hash[kv])	
			createSymlink(igvMutationSourcePath, alignedPath + "/" + cgsKey, cgsKey + "_" + kv, files_hash[kv])

if __name__ == "__main__":
	#Read in config
	config = ConfigParser.RawConfigParser()
	config.read('./cgs_lims.config')
        cgs_submit(sys.argv[1], "symlink_webpath_tomcat", config) 
